package com.jiazhong.Servlet;

import com.jiazhong.Model.User;
import com.jiazhong.Service.Impl.UserServiceImpl;
import com.jiazhong.Service.UserService;
import com.jiazhong.exceptions.BadPasswordException;
import com.jiazhong.exceptions.UsernameNotFoundException;
import com.jiazhong.utils.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;


@WebServlet("/authentication.do")
public class AuthenticationServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    /**
     * 用户登录的Servlet方法
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            User user = Utils.encapsulationRequestToBean(User.class, request);
            //调用业务层进行处理
            User curUser = userService.login(user.getUser_name(), user.getUser_password());
            //将curUser存入到session中
            request.getSession().setAttribute("user", curUser);
            response.sendRedirect("/index.jsp");
        } catch (UsernameNotFoundException e) {//用户名错误
            response.sendRedirect("/login.jsp?errMSG=" + URLEncoder.encode(e.getMessage(), "UTF-8"));
        } catch (BadPasswordException e) {//密码错误
            response.sendRedirect("/login.jsp?errMSG=" + URLEncoder.encode(e.getMessage(), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 用户注册servlet方法
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            User user = Utils.encapsulationRequestToBean(User.class, request);
            userService.register(user);
            response.sendRedirect("/index.jsp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户退出
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //销毁session
        //request.getSession().invalidate();//销毁session
        //从session中移除user属性
        request.getSession().removeAttribute("user");
        response.sendRedirect("/index.jsp");

    }

    }
